<template>
  <div>
    <input
      ref="input"
      type="file"
      style="display:none"
      accept=".xlsx"
      @change="change"
    />
  </div>
</template>

<script>
import Excel from "exceljs";
import FileSaver from "file-saver";
import { isArray, isString } from "@/utils/validate.js";
export default {
  name: "meiExcelHelp",
  data() {
    return {
      EXCEL_TYPE:
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"
    };
  },
  //外部属性
  props: {},
  //内部方法
  methods: {
    initPage() {},
    //文件变更
    async change(e) {
      const files = e.target.files;
      let fileReader = new FileReader();
      fileReader.onload = async ev => {
        //this.$emit('change',data);
        const data = ev.target.result;
        const workbook = new Excel.Workbook();
        await workbook.xlsx.load(data);
        let newdata = [], //数据
          cols = []; //列
        //读sheet 页签
        workbook.eachSheet((worksheet, sheetId) => {
          //从1开始 就读第一页
          if (sheetId == 1) {
            //读行
            worksheet.eachRow((row, rowNumber) => {
              //第一行是列头
              if (rowNumber == 1) {
                row.eachCell(cell => {
                  cols.push(cell.value);
                });
              } else {
                let newrow = {};
                //第二行 读单元格
                row.eachCell((cell, colNumber) => {
                  Object.assign(newrow, {
                    [cols[colNumber - 1]]: cell.value
                  });
                });
                //加入行
                newdata.push(newrow);
              }
            });
            //触发事件
            this.$emit("readExcel", newdata, cols, worksheet, workbook);
          }
        });
      };
      fileReader.readAsBinaryString(files[0]);
    },
    //触犯选择文件
    select() {
      this.$refs.input.click();
    },
    /**
     * @description 下载方法
     * @param {Array} data 数据集合 如果数组对象是字符串那么只是列头
     * @param {String} title = "download" 文件名称
     * @param {String} sheetname = "Sheet1" sheet名称
     */
    async downLoad(data = [], title = "download", sheetname = "Sheet1") {
      //创建文件
      const workbook = new Excel.Workbook();
      //新建页签
      const sheet = workbook.addWorksheet(sheetname);
      //如果是数组
      if (!isArray(data)) {
        return;
      }
      //如果都是string
      const bstr = data.every(item => isString(item));
      //新建数据 A B C ...
      bstr && sheet.addRow([...data]);
      if (!bstr) {
        //如果不是字符串 循环 提取值的数据 加入行
        data.forEach(item => {
          if (item) {
            sheet.addRow(Object.values(item));
          }
        });
      }
      sheet.eachRow((row, rowNumber) => {
        //第一行是列头
        if (rowNumber == 1) {
          row.eachCell(cell => {
            cell.border = {
              top: { style: "thin" },
              left: { style: "thin" },
              bottom: { style: "thin" },
              right: { style: "thin" }
            };
            cell.fill = {
              type: "pattern",
              pattern: "solid",
              bgColor: { argb: "FF0000FF" }
            };
          });
        }
      });
      //转为二进制
      const buffer = await workbook.xlsx.writeBuffer();
      //输出下载
      const blob = new Blob([buffer], { type: this.EXCEL_TYPE });
      FileSaver.saveAs(blob, `${title}.xlsx`);
    }
  },
  //组件
  components: {},
  //初始化 异步加async await
  mounted() {
    this.initPage();
  },
  //计算属性
  computed: {},
  //监视
  watch: {}
};
</script>

<style lang="scss" scoped>
@import "@/style/base.scss";
</style>
